package com.qkl.xiatang.app.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qkl.xiatang.app.cache.LocalCacheBuilder;
import com.qkl.xiatang.app.cache.LocalSimpleCache;
import com.qkl.xiatang.app.config.AppConfig;
import com.qkl.xiatang.app.entity.AppURL;
import com.qkl.xiatang.app.mapper.AppURLMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
@Slf4j
public class AppURLService {

    @Autowired
    private AppURLMapper urlMapper;

    @Autowired
    private AppConfig appConfig;

    @Value("${app.openApi}")
    private String openApi;

    private LocalSimpleCache<Set<String>> urlCache;

    /**
     * 查询不拦截 UR
     * @return
     */
    public List<AppURL> queryNotInterceptURLs(){
        return urlMapper.selectList(new QueryWrapper<AppURL>().eq("status",0));
    }

    public boolean notIntercept(String url){
        return urlCache.getCache().contains(url) || url.contains(openApi);
    }

    @PostConstruct
    public void initUrlCache(){
        LocalCacheBuilder<Set<String>> builder = new LocalCacheBuilder<>();
        urlCache = builder.build(30,null,()-> queryURLs());
    }

    private Set<String> queryURLs(){
        List<AppURL> urls = this.queryNotInterceptURLs();
        Set<String> set = new HashSet<>();
        if(ObjectUtils.isNotEmpty(urls)){
            String contextPath = StringUtils.trimToEmpty(appConfig.getServerContextPath());
            for(AppURL url : urls){
                set.add(contextPath + StringUtils.trimToEmpty(url.getUrl()));
            }
        }
        return set;
    }

}
